<template>
  <view class="room-seat-query-container">
    <view class="page-header">
      <text class="page-title">房间席位</text>
      <text class="page-subtitle">房间: {{ roomName }}</text>
      <view class="room-status-section">
        <view class="current-status">
          <text class="status-label">当前状态:</text>
          <view class="status-badge" :class="getRoomStatusClass(roomStatus)">
            {{ getRoomStatusText(roomStatus) }}
          </view>
        </view>
        <button class="update-status-btn" @click="openStatusUpdateModal" :disabled="updatingStatus">
          {{ updatingStatus ? '更新中...' : '修改状态' }}
        </button>
      </view>
      <!-- WebSocket连接控制 -->
      <view class="ws-connection-section">
        <text class="ws-status-label">WebSocket:</text>
        <view class="ws-status-indicator" :class="{ 'connected': connected, 'disconnected': !connected }">
          {{ connected ? '已连接' : '未连接' }}
        </view>
        <button class="ws-connect-btn" v-if="!connected" @click="connectServer" :disabled="connecting">{{ connecting ? '连接中...' : '连接WebSocket' }}</button>
        <button class="ws-disconnect-btn" v-else @click="disconnectServer">断开WebSocket</button>
      </view>
    </view>

    <view class="seat-list-section">
      <view class="list-header">
        <view class="header-actions">
          <button class="create-btn" @click="openAddSeatModal">添加席位</button>
          <button class="result-btn" @click="goToRoomResult">查询结果</button>
          <button class="join-btn" @click="joinRoom">加入房间</button>
        </view>
      </view>

      <view v-if="loading" class="loading-container">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="seatList.length === 0" class="empty-state">
        <text>该房间下暂无席位</text>
      </view>

      <view v-else class="seat-list">
        <view 
          class="seat-item" 
          v-for="seat in seatList" 
          :key="seat.id"
        >
          <view class="seat-header">
            <text class="seat-id">席位ID: {{ seat.id }}</text>
            <view class="seat-status" :class="getStatusClass(seat.status)">
              {{ getStatusText(seat.status) }}
            </view>
          </view>
          
          <view class="seat-info">
            <view class="info-row">
              <text class="info-label">席位所有者:</text>
              <text class="info-value">{{ seat.owner || '未分配' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">角色权限:</text>
              <text class="info-value">{{ getRoleText(seat.role) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">签到时间:</text>
              <text class="info-value">{{ formatDate(seat.signTime) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">创建时间:</text>
              <text class="info-value">{{ formatDate(seat.createTime) }}</text>
            </view>
          </view>
          
          <view class="seat-actions">
            <button class="detail-btn" @click="goToSeatDetail(seat)">详情</button>
            <button class="edit-btn" @click="editSeat(seat)">编辑</button>
            <button class="update-status-btn" @click="openSeatStatusUpdateModal(seat)" :disabled="updatingSeatStatus">
              {{ updatingSeatStatus ? '更新中...' : '修改状态' }}
            </button>
            <button class="delete-btn" @click="deleteSeat(seat)">删除</button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 添加/编辑席位模态框 -->
    <view class="modal-overlay" v-if="showSeatFormModal" @click="closeSeatFormModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ isEditingSeat ? '编辑席位' : '添加席位' }}</text>
          <button class="close-btn" @click="closeSeatFormModal">×</button>
        </view>
        
        <view class="modal-body">
          <view class="form-section">
            <view class="form-item">
              <text class="form-label">席位所有者</text>
              <input 
                class="form-input" 
                v-model="seatForm.owner" 
                placeholder="请输入席位所有者ID"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">角色权限</text>
              <view class="form-picker" @click="openRolePicker">
                <view class="picker-text">{{ roleOptions[roleIndex] || '请选择角色权限' }}</view>
                <view class="picker-arrow">▼</view>
              </view>
            </view>
            
            <view class="form-item">
              <text class="form-label">席位状态</text>
              <view class="form-picker" @click="openStatusPicker">
                <view class="picker-text">{{ statusOptions[statusIndex] || '请选择席位状态' }}</view>
                <view class="picker-arrow">▼</view>
              </view>
            </view>
       
            
            <view class="form-item">
              <text class="form-label">房间组ID</text>
              <input 
                class="form-input" 
                v-model="seatForm.matchRoomGroupId" 
                placeholder="请输入房间组ID"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">日程注册ID</text>
              <input 
                class="form-input" 
                v-model="seatForm.matchScheduleRegId" 
                placeholder="请输入日程注册ID"
              />
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeSeatFormModal">取消</button>
          <button class="submit-btn" @click="saveSeat" :disabled="submitting">
            {{ submitting ? '保存中...' : '保存' }}
          </button>
        </view>
      </view>
    </view>
    
    <!-- 角色权限选择模态框 -->
    <view class="modal-overlay" v-if="showRolePicker" @click="closeRolePicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择角色权限</text>
          <button class="close-btn" @click="closeRolePicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in roleOptions" 
            :key="index"
            @click="selectRole(index)"
            :class="{ 'selected': roleIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="roleIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 席位状态选择模态框 -->
    <view class="modal-overlay" v-if="showStatusPicker" @click="closeStatusPicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择席位状态</text>
          <button class="close-btn" @click="closeStatusPicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in statusOptions" 
            :key="index"
            @click="selectStatus(index)"
            :class="{ 'selected': statusIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="statusIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 席位事件选择模态框 -->
    <view class="modal-overlay" v-if="showEventPicker" @click="closeEventPicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择席位事件</text>
          <button class="close-btn" @click="closeEventPicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in eventOptions" 
            :key="index"
            @click="selectEvent(index)"
            :class="{ 'selected': eventIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="eventIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 房间状态更新模态框 -->
    <view class="modal-overlay" v-if="showStatusUpdateModal" @click="closeStatusUpdateModal">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">修改房间状态</text>
          <button class="close-btn" @click="closeStatusUpdateModal">×</button>
        </view>
        <view class="modal-body">
          <view class="current-status-info">
            <text class="info-label">当前状态:</text>
            <view class="status-badge" :class="getRoomStatusClass(roomStatus)">
              {{ getRoomStatusText(roomStatus) }}
            </view>
          </view>
          <view class="next-status-section">
            <text class="section-title">选择下一个状态:</text>
            <view class="status-options">
              <view 
                class="status-option" 
                v-for="(status, index) in availableNextStatuses" 
                :key="status.value"
                @click="selectNextStatus(status.value)"
                :class="{ 'selected': selectedNextStatus === status.value }"
              >
                <text class="option-text">{{ status.label }}</text>
                <view class="option-check" v-if="selectedNextStatus === status.value">✓</view>
              </view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeStatusUpdateModal">取消</button>
          <button class="submit-btn" @click="updateRoomStatus" :disabled="updatingStatus">
            {{ updatingStatus ? '更新中...' : '确认更新' }}
          </button>
        </view>
      </view>
    </view>
    
    <!-- 席位状态更新模态框 -->
    <view class="modal-overlay" v-if="showSeatStatusUpdateModal" @click="closeSeatStatusUpdateModal">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">修改席位状态</text>
          <button class="close-btn" @click="closeSeatStatusUpdateModal">×</button>
        </view>
        <view class="modal-body">
          <view class="current-status-info">
            <text class="info-label">席位ID:</text>
            <text class="info-value">{{ currentSeatForStatus?.id }}</text>
          </view>
          <view class="current-status-info">
            <text class="info-label">当前状态:</text>
            <view class="status-badge" :class="getStatusClass(currentSeatForStatus?.status)">
              {{ getStatusText(currentSeatForStatus?.status) }}
            </view>
          </view>
          <view class="next-status-section">
            <text class="section-title">选择下一个状态:</text>
            <view class="status-options">
              <view 
                class="status-option" 
                v-for="(status, index) in availableNextSeatStatuses" 
                :key="status.value"
                @click="selectNextSeatStatus(status.value)"
                :class="{ 'selected': selectedNextSeatStatus === status.value }"
              >
                <text class="option-text">{{ status.label }}</text>
                <view class="option-check" v-if="selectedNextSeatStatus === status.value">✓</view>
              </view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeSeatStatusUpdateModal">取消</button>
          <button class="submit-btn" @click="updateSeatStatus" :disabled="updatingSeatStatus">
            {{ updatingSeatStatus ? '更新中...' : '确认更新' }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchRoomSeatAPI, MatchRoomAPI, BattleAPI } from '@/api/battle.js'
import { useUserStore } from '@/stores/user.js'
import globalWebSocket from '@/utils/globalWebSocket.js'

const loading = ref(false)
const seatList = ref([])
const roomId = ref('')
const roomName = ref('')
const matchScheduleId = ref('')

// 房间状态管理相关数据
const roomStatus = ref(1) // 默认等待状态
const showStatusUpdateModal = ref(false)
const updatingStatus = ref(false)
const selectedNextStatus = ref(null)

// 席位状态管理相关数据
const showSeatStatusUpdateModal = ref(false)
const updatingSeatStatus = ref(false)
const selectedNextSeatStatus = ref(null)
const currentSeatForStatus = ref(null)

// 席位表单相关数据
const showSeatFormModal = ref(false)
const submitting = ref(false)
const isEditingSeat = ref(false)
const currentSeat = ref(null)

// 选择器相关数据
const showRolePicker = ref(false)
const showStatusPicker = ref(false)
const showEventPicker = ref(false)

// 席位表单数据
const seatForm = ref({
  owner: '',
  role: 1,  // 默认选择选手
  status: 0,
  event: 0,
  matchRoomGroupId: '',
  matchScheduleRegId: ''
})

const roleIndex = ref(0)  // 默认选择第一个选项（选手）
const statusIndex = ref(0)
const eventIndex = ref(0)

// WebSocket相关数据
const userStore = useUserStore()
const socketAdapter = ref(null)
const connected = ref(false)
const connecting = ref(false)

// 初始化Socket适配器
const initSocketAdapter = async () => {
  try {
    console.log('room-seat-query: 开始初始化WebSocket连接...')
    socketAdapter.value = await globalWebSocket.getConnection()
    connected.value = globalWebSocket.isConnected()
    console.log('room-seat-query: 使用全局WebSocket连接，连接状态:', connected.value)
    
    if (socketAdapter.value && connected.value) {
      console.log('room-seat-query: WebSocket连接成功，可以发送消息')
      // 连接成功后自动发送加入房间消息
      setTimeout(() => {
        if (roomId.value && socketAdapter.value) {
          socketAdapter.value.sendRoomStatusChange(roomId.value, 1) // event=1表示玩家加入
          console.log('room-seat-query: 自动发送加入房间消息:', roomId.value)
        }
      }, 1000) // 延迟1秒确保登录完成
    }
  } catch (error) {
    console.error('room-seat-query: 获取WebSocket连接失败:', error)
    connected.value = false
  }
}

// 房间事件选项 - 根据新的事件值重新定义
const roomEventOptions = [
  '',                    // 0: 占位
  '玩家加入',           // 1: PLAYER_JOIN
  '玩家离开',           // 2: PLAYER_LEAVE
  '所有席位准备就绪',    // 3: ALL_READY
  '开始倒计时',         // 4: START_COUNTDOWN
  '开始比赛',           // 5: START_GAME
  '暂停比赛',           // 6: PAUSE_GAME
  '恢复比赛',           // 7: RESUME_GAME
  '结束比赛',           // 8: END_GAME
  '取消比赛',           // 9: CANCEL_GAME
  '重新开始比赛',       // 10: RESTART_GAME
  '发生异常'            // 99: ERROR_OCCURRED
]

// 房间状态转换规则（根据当前状态确定可用的下一个状态）
const getAvailableNextStatuses = (currentStatus) => {
  // 状态转换规则（当前状态 -> 可用的下一个事件）
  const statusTransitions = {
    1: [1, 9, 99], // 等待 -> 玩家加入/取消比赛/发生异常
    2: [3, 9, 99], // 准备 -> 所有席位准备就绪/取消比赛/发生异常
    3: [5, 6, 9, 99], // 倒计时 -> 开始比赛/暂停比赛/取消比赛/发生异常
    4: [6, 8, 9, 99], // 开始比赛 -> 暂停比赛/结束比赛/取消比赛/发生异常
    5: [2, 9, 10, 99], // 结束比赛 -> 等待/取消比赛/重新开始比赛/发生异常
    6: [7, 9, 99], // 暂停 -> 恢复比赛/取消比赛/发生异常
    7: [2, 99], // 取消 -> 等待/发生异常
    8: [2, 7, 10, 99] // 异常 -> 等待/取消/重新开始比赛/发生异常
  }
  
  const availableEvents = statusTransitions[currentStatus] || []
  return availableEvents.map(event => ({
    value: event, // 直接使用事件值
    label: roomEventOptions[event] || '未知事件'
  }))
}

// 计算可用的下一个状态
const availableNextStatuses = ref([])

const statusOptions = [
  '空闲',
  '占用',
  '准备-等待比赛开始',
  '赛前准备',
  '策略规划',
  '比赛',
  '比赛结束',
  '异常'
]

const eventOptions = [
  '加入',           // 0: JOIN
  '准备',           // 1: READY
  '开始赛前准备',    // 2: START_PREPARE
  '策略规划',       // 3: STRATEGY_PLANNING
  '开始比赛',       // 4: START_GAME
  '结束比赛',       // 5: END_GAME
  '离开',           // 6: LEAVE
  '发生异常',       // 7: ERROR_OCCURRED
  '重新开始比赛'    // 8: RESTART_GAME
]

const roleOptions = [
  '选手',
  '裁判',
  '观众', 
  '主持人',
  '替补选手'
]

// 房间状态映射
const roomStatusMap = {
  1: '等待',
  2: '准备',
  3: '倒计时',
  4: '开始比赛',
  5: '结束比赛',
  6: '暂停',
  7: '取消/终止',
  8: '异常'
}

// 房间状态样式映射
const roomStatusClassMap = {
  1: 'status-wait',
  2: 'status-prepare',
  3: 'status-countdown',
  4: 'status-start',
  5: 'status-stop',
  6: 'status-pause',
  7: 'status-cancel',
  8: 'status-error'
}

// 席位状态映射
const statusMap = {
  0: '空闲',
  1: '占用',
  2: '准备-等待比赛开始',
  3: '赛前准备',
  4: '策略规划',
  5: '比赛',
  6: '比赛结束',
  99: '异常'
}

// 席位状态样式映射
const statusClassMap = {
  0: 'status-idle',
  1: 'status-occupy',
  2: 'status-ready',
  3: 'status-prepare',
  4: 'status-plan',
  5: 'status-matching',
  6: 'status-end',
  99: 'status-error'
}

// 席位事件映射
const eventMap = {
  0: '加入',
  1: '准备',
  2: '开始赛前准备',
  3: '策略规划',
  4: '开始比赛',
  5: '结束比赛',
  6: '离开',
  7: '发生异常',
  8: '重新开始比赛'
}

// 角色权限映射
const roleMap = {
  1: '选手',
  2: '裁判', 
  3: '观众',
  4: '主持人',
  5: '替补选手'
}

const getStatusText = (status) => statusMap[status] || '未知'
const getStatusClass = (status) => statusClassMap[status] || 'status-unknown'
const getEventText = (event) => eventMap[event] || '未知'
const getRoleText = (role) => roleMap[role] || '未知'
const getRoomStatusText = (status) => roomStatusMap[status] || '未知'
const getRoomStatusClass = (status) => roomStatusClassMap[status] || 'status-unknown'

const formatDate = (timestamp) => {
  if (!timestamp) return '未设置'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

// 获取房间信息（包括状态）
const fetchRoomInfo = async () => {
  if (!roomId.value) return
  
  try {
    console.log('获取房间信息，房间ID:', roomId.value)
    const result = await MatchRoomAPI.page({
      matchRoomId: roomId.value,
      pageNum: 0,
      pageSize: 1
    })
    
    if (result.code === 0 && result.data) {
      const roomData = Array.isArray(result.data) ? result.data[0] : result.data.list?.[0]
      if (roomData) {
        roomStatus.value = roomData.status || 1
        matchScheduleId.value = roomData.matchScheduleId || ''
        console.log('获取到房间状态:', roomStatus.value)
        console.log('获取到赛程ID:', matchScheduleId.value)
      }
    }
  } catch (error) {
    console.error('获取房间信息失败:', error)
    // 如果获取失败，使用默认状态
    roomStatus.value = 1
  }
}

// 打开状态更新模态框
const openStatusUpdateModal = () => {
  availableNextStatuses.value = getAvailableNextStatuses(roomStatus.value)
  selectedNextStatus.value = null
  showStatusUpdateModal.value = true
}

// 关闭状态更新模态框
const closeStatusUpdateModal = () => {
  showStatusUpdateModal.value = false
  selectedNextStatus.value = null
}

// 选择下一个状态
const selectNextStatus = (status) => {
  selectedNextStatus.value = status
}

// 更新房间状态
const updateRoomStatus = async () => {
  if (selectedNextStatus.value === null) {
    uni.showToast({
      title: '请选择要更新的状态',
      icon: 'none'
    })
    return
  }
  
  // 保存event值，避免被清空
  const eventValue = selectedNextStatus.value
  
  updatingStatus.value = true
  try {
    const result = await BattleAPI.updateRoomStatus({
      matchRoomId: roomId.value,
      event: eventValue
    })
    
    console.log('更新房间状态API返回结果:', result)
    
    if (result.code === 0) {
      uni.showToast({
        title: '状态更新成功',
        icon: 'success'
      })
      
      closeStatusUpdateModal()
      
      // 重新获取房间信息以获取最新状态
      await fetchRoomInfo()
      // WebSocket发送房间状态变更消息（新协议）
      if (socketAdapter.value && connected.value) {
        socketAdapter.value.sendRoomStatusChange(roomId.value, eventValue)
      }
    } else {
      throw new Error(result.msg || '状态更新失败')
    }
  } catch (error) {
    console.error('更新房间状态失败:', error)
    uni.showToast({
      title: error.message || '状态更新失败',
      icon: 'none'
    })
  } finally {
    updatingStatus.value = false
  }
}

const fetchSeatList = async () => {
  if (!roomId.value) return;
  loading.value = true
  try {
    const result = await MatchRoomSeatAPI.page({ 
      matchRoomId: roomId.value,
      pageNum: 0,
      pageSize: 100
    })
    console.log('席位查询API返回结果:', result)
    if (result.code === 0) {
      seatList.value = result.data?.list || result.data || []
    } else {
      seatList.value = []
      throw new Error(result.msg || '获取席位失败')
    }
  } catch (error) {
    console.error('获取席位失败:', error)
    uni.showToast({
      title: error.message || '获取席位失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

onLoad((options) => {
  if (options.roomId) {
    roomId.value = options.roomId
    roomName.value = decodeURIComponent(options.roomName || '')
    fetchRoomInfo()
    fetchSeatList()
  }
  if (options.matchScheduleId) {
    matchScheduleId.value = options.matchScheduleId
  }
})

// 页面卸载时清理资源（不断开全局WebSocket连接）
onUnmounted(() => {
  console.log('room-seat-query页面卸载，保持全局WebSocket连接')
  // 不调用 socketAdapter.value.disconnect()，保持全局连接
  // 只清理页面相关的定时器或其他资源
})

// 编辑席位
const editSeat = (seat) => {
  isEditingSeat.value = true
  currentSeat.value = seat
  fillSeatForm(seat)
  showSeatFormModal.value = true
}

// 删除席位
const deleteSeat = (seat) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除席位 "${seat.owner || seat.id}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await MatchRoomSeatAPI.remove({
            matchRoomSeatId: seat.id
          })
          
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            fetchSeatList()
          } else {
            throw new Error(result.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除席位失败:', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 打开添加席位模态框
const openAddSeatModal = () => {
  isEditingSeat.value = false
  currentSeat.value = null
  resetSeatForm()
  showSeatFormModal.value = true
}

// 关闭席位表单模态框
const closeSeatFormModal = () => {
  showSeatFormModal.value = false
  isEditingSeat.value = false
  currentSeat.value = null
  resetSeatForm()
}

// 重置席位表单
const resetSeatForm = () => {
  seatForm.value = {
    owner: '',
    role: 1,  // 默认选择选手
    status: 0,
    event: 0,
    matchRoomGroupId: '',
    matchScheduleRegId: ''
  }
  roleIndex.value = 0
  statusIndex.value = 0
  eventIndex.value = 0
}

// 填充席位表单
const fillSeatForm = (seat) => {
  seatForm.value = {
    owner: seat.owner || '',
    role: seat.role || 1,
    status: seat.status || 0,
    event: seat.event || 0,
    matchRoomGroupId: seat.matchRoomGroupId || '',
    matchScheduleRegId: seat.matchScheduleRegId || ''
  }
  roleIndex.value = (seat.role || 1) - 1  // 角色值从1开始，索引从0开始
  statusIndex.value = seat.status || 0
  eventIndex.value = seat.event || 0
}

// 打开角色权限选择器
const openRolePicker = () => {
  showRolePicker.value = true
}

// 关闭角色权限选择器
const closeRolePicker = () => {
  showRolePicker.value = false
}

// 选择角色权限
const selectRole = (index) => {
  roleIndex.value = index
  seatForm.value.role = index + 1  // 角色值从1开始
  closeRolePicker()
}

// 打开席位状态选择器
const openStatusPicker = () => {
  showStatusPicker.value = true
}

// 关闭席位状态选择器
const closeStatusPicker = () => {
  showStatusPicker.value = false
}

// 选择席位状态
const selectStatus = (index) => {
  statusIndex.value = index
  seatForm.value.status = index === 7 ? 99 : index
  closeStatusPicker()
}

// 打开席位事件选择器
const openEventPicker = () => {
  showEventPicker.value = true
}

// 关闭席位事件选择器
const closeEventPicker = () => {
  showEventPicker.value = false
}

// 选择席位事件
const selectEvent = (index) => {
  eventIndex.value = index
  seatForm.value.event = index
  closeEventPicker()
}

// 保存席位
const saveSeat = async () => {
  if (!seatForm.value.owner.trim()) {
    uni.showToast({
      title: '请输入席位所有者',
      icon: 'none'
    })
    return
  }
  
  submitting.value = true
  try {
    const data = {
      matchRoomId: roomId.value,
      owner: seatForm.value.owner,
      role: seatForm.value.role,
      status: seatForm.value.status,
      event: seatForm.value.event,
      matchRoomGroupId: seatForm.value.matchRoomGroupId,
      matchScheduleRegId: seatForm.value.matchScheduleRegId
    }
    
    let result
    if (isEditingSeat.value) {
      result = await MatchRoomSeatAPI.edit({
        ...data,
        matchRoomSeatId: currentSeat.value.id
      })
    } else {
      result = await MatchRoomSeatAPI.create(data)
    }
    
    if (result.code === 0) {
      uni.showToast({
        title: isEditingSeat.value ? '更新成功' : '创建成功',
        icon: 'success'
      })
      closeSeatFormModal()
      fetchSeatList()
    } else {
      throw new Error(result.msg || (isEditingSeat.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('保存席位失败:', error)
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 席位状态转换规则（根据当前状态确定可用的下一个状态）
const getAvailableNextSeatStatuses = (currentStatus) => {
  // 状态转换规则（当前状态 -> 可用的下一个事件）
  const statusTransitions = {
    0: [0, 7], // 空闲 -> 加入/发生异常
    1: [1, 7], // 占用 -> 准备/发生异常
    2: [2, 7], // 准备-等待比赛开始 -> 开始赛前准备/发生异常
    3: [3, 7], // 赛前准备 -> 策略规划/发生异常
    4: [4, 7], // 策略规划 -> 开始比赛/发生异常
    5: [5, 7], // 比赛 -> 结束比赛/发生异常
    6: [6, 7, 8], // 比赛结束 -> 离开/发生异常/重新开始比赛
    99: [0, 7, 8] // 异常 -> 加入/发生异常/重新开始比赛
  }
  
  const availableEvents = statusTransitions[currentStatus] || []
  return availableEvents.map(event => ({
    value: event, // 直接使用事件值
    label: eventOptions[event] || '未知事件'
  }))
}

// 计算可用的下一个席位状态
const availableNextSeatStatuses = ref([])

// 打开席位状态更新模态框
const openSeatStatusUpdateModal = (seat) => {
  currentSeatForStatus.value = seat
  availableNextSeatStatuses.value = getAvailableNextSeatStatuses(seat.status)
  selectedNextSeatStatus.value = null
  showSeatStatusUpdateModal.value = true
}

// 关闭席位状态更新模态框
const closeSeatStatusUpdateModal = () => {
  showSeatStatusUpdateModal.value = false
  selectedNextSeatStatus.value = null
  // currentSeatForStatus.value = null // 移除这里的清空
}

// 选择下一个席位状态
const selectNextSeatStatus = (status) => {
  selectedNextSeatStatus.value = status
}

// 更新席位状态
const updateSeatStatus = async () => {
  if (selectedNextSeatStatus.value === null) {
    uni.showToast({
      title: '请选择要更新的状态',
      icon: 'none'
    })
    return
  }
  if (!currentSeatForStatus.value) {
    uni.showToast({
      title: '席位信息不存在',
      icon: 'none'
    })
    return
  }
  
  // 保存event值，避免被清空
  const eventValue = selectedNextSeatStatus.value
  
  updatingSeatStatus.value = true
  try {
    const result = await BattleAPI.updateRoomSeatStatus({
      matchRoomSeatId: currentSeatForStatus.value.id,
      event: eventValue
    })
    if (result.code === 0) {
      uni.showToast({
        title: '席位状态更新成功',
        icon: 'success'
      })
      closeSeatStatusUpdateModal()
      // 重新获取席位列表以获取最新状态
      await fetchSeatList()
      // WebSocket发送席位状态变更消息（新协议）
      if (
        socketAdapter.value && 
        connected.value && 
        currentSeatForStatus.value && 
        currentSeatForStatus.value.id
      ) {
        socketAdapter.value.sendRoomSeatStatusChange(currentSeatForStatus.value.id, eventValue, roomId.value)
      }
      // 在所有异步操作完成后再清空
      currentSeatForStatus.value = null
    } else {
      throw new Error(result.msg || '席位状态更新失败')
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '席位状态更新失败',
      icon: 'none'
    })
  } finally {
    updatingSeatStatus.value = false
  }
}

// 跳转到席位详情页面
const goToSeatDetail = (seat) => {
  uni.navigateTo({
    url: `/views/seat-detail?seatId=${seat.id}&seatName=${encodeURIComponent(seat.owner || '席位' + seat.id)}`
  })
}

// 加入房间
const joinRoom = async () => {
  if (!roomId.value) {
    uni.showToast({
      title: '房间ID不存在',
      icon: 'none'
    })
    return
  }
  try {
    uni.showLoading({ title: '正在加入房间...' })
    const result = await BattleAPI.joinRoom({
      appId: 1,
      channel: 10001,
      matchRoomId: roomId.value,
      matchScheduleId: matchScheduleId.value,
      pageNum: 0,
      pageSize: 10
    })
    if (result.code === 0) {
      uni.showToast({
        title: '加入房间成功',
        icon: 'success'
      })
      fetchSeatList()
      // WebSocket发送房间状态变更消息（新协议，event=1表示加入房间）
      if (socketAdapter.value && connected.value) {
        socketAdapter.value.sendRoomStatusChange(roomId.value, 1)
      }
    } else {
      throw new Error(result.msg || '加入房间失败')
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '加入房间失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 跳转到房间结果页面
const goToRoomResult = () => {
  if (!roomId.value) {
    uni.showToast({
      title: '房间ID不存在',
      icon: 'none'
    })
    return
  }
  
  uni.navigateTo({
    url: `/views/room-result?roomId=${roomId.value}&roomName=${encodeURIComponent(roomName.value)}`
  })
}

// 组件挂载时初始化
onMounted(async () => {
  await initSocketAdapter()
  // 不再需要手动调用 connect()，全局WebSocket管理器已经处理了连接
})

// 组件卸载时清理
onUnmounted(() => {
  if (connected.value && socketAdapter.value) {
    socketAdapter.value.disconnect()
  }
})

// WebSocket连接/断开方法
const connectServer = async () => {
  connecting.value = true
  try {
    socketAdapter.value = await globalWebSocket.getConnection()
    connected.value = globalWebSocket.isConnected()
    if (connected.value) {
      uni.showToast({ title: 'WebSocket连接成功', icon: 'success' })
    } else {
      throw new Error('连接失败')
    }
  } catch (err) {
    uni.showToast({ title: err.message || '连接失败', icon: 'none' })
  } finally {
    connecting.value = false
  }
}

const disconnectServer = () => {
  globalWebSocket.disconnect()
  socketAdapter.value = null
  connected.value = false
  uni.showToast({ title: 'WebSocket已断开', icon: 'success' })
}
</script>

<style lang="scss" scoped>
.room-seat-query-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
}

.page-header {
  text-align: center;
  margin-bottom: 60rpx;
  
  .page-title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 20rpx;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
  }
  
  .page-subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }

  .room-status-section {
    margin-top: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    .current-status {
      margin-right: 20rpx;

      .status-label {
        font-size: 28rpx;
        color: rgba(255, 255, 255, 0.8);
      }

      .status-badge {
        padding: 8rpx 20rpx;
        border-radius: 20rpx;
        font-size: 24rpx;
        font-weight: bold;
        margin-left: 10rpx;

        &.status-wait { background: #fff3cd; color: #856404; }
        &.status-prepare { background: #d1ecf1; color: #0c5460; }
        &.status-countdown { background: #d4edda; color: #155724; }
        &.status-start { background: #cce5ff; color: #004085; }
        &.status-stop { background: #f8d7da; color: #721c24; }
        &.status-pause { background: #fff3cd; color: #856404; }
        &.status-cancel { background: #f8d7da; color: #721c24; }
        &.status-error { background: #f8d7da; color: #721c24; }
      }
    }

    .update-status-btn {
      padding: 8rpx 20rpx;
      border: none;
      border-radius: 12rpx;
      color: #fff;
      font-size: 24rpx;
      font-weight: bold;
      background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
      
      &:disabled {
        opacity: 0.6;
      }
    }
  }
}

.seat-list-section {
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .section-title {
      color: #fff;
      font-size: 32rpx;
      font-weight: bold;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
      gap: 15rpx;
      
      .create-btn {
        height: 60rpx;
        padding: 0 25rpx;
        border: none;
        border-radius: 12rpx;
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
      }
      
      .result-btn {
        height: 60rpx;
        padding: 0 25rpx;
        border: none;
        border-radius: 12rpx;
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
        background: linear-gradient(135deg, #6f42c1 0%, #5a32a3 100%);
      }
      
      .join-btn {
        height: 60rpx;
        padding: 0 25rpx;
        border: none;
        border-radius: 12rpx;
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
        background: linear-gradient(135deg, #6f42c1 0%, #5a32a3 100%);
      }
      
      .list-count {
        color: rgba(255, 255, 255, 0.8);
        font-size: 24rpx;
      }
    }
  }

  .loading-container, .empty-state {
    text-align: center;
    color: #fff;
    padding: 50rpx;
  }
  
  .seat-list .seat-item {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 40rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
      
    .seat-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      
      .seat-id {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .seat-status {
        padding: 8rpx 20rpx;
        border-radius: 20rpx;
        font-size: 24rpx;
        font-weight: bold;
        
        &.status-idle { background: #d4edda; color: #155724; }
        &.status-occupy { background: #cce5ff; color: #004085; }
        &.status-ready { background: #fff3cd; color: #856404; }
        &.status-prepare { background: #d1ecf1; color: #0c5460; }
        &.status-plan { background: #e2e3e5; color: #383d41; }
        &.status-matching { background: #d4edda; color: #155724; }
        &.status-end { background: #f8d7da; color: #721c24; }
        &.status-error { background: #f8d7da; color: #721c24; }
      }
    }
      
    .seat-info {
      .info-row {
        display: flex;
        margin-bottom: 15rpx;
        font-size: 26rpx;
        
        .info-label { 
          width: 160rpx; 
          color: #666; 
        }
        .info-value { 
          flex: 1; 
          color: #333; 
        }
      }
    }
    
    .seat-actions {
      display: flex;
      gap: 15rpx;
      justify-content: flex-end;
      margin-top: 20rpx;
      
      .detail-btn, .edit-btn, .update-status-btn, .delete-btn {
        padding: 8rpx 20rpx;
        border: none;
        border-radius: 12rpx;
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
      }
      
      .detail-btn {
        background: linear-gradient(135deg, #6f42c1 0%, #5a32a3 100%);
      }
      
      .edit-btn {
        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
      }
      
      .update-status-btn {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
      }
      
      .delete-btn {
        background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
      }
    }
  }
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 选择器模态框样式
.picker-modal-content {
  width: 80%;
  max-height: 70%;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  position: relative;
  z-index: 10001;
  
  .picker-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 2rpx solid #eee;
    background: #f8f9fa;
    
    .picker-modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-btn {
      width: 60rpx;
      height: 60rpx;
      border: none;
      background: none;
      font-size: 40rpx;
      color: #999;
    }
  }
  
  .picker-modal-body {
    max-height: 50vh;
    overflow-y: auto;
    
    .picker-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #eee;
      transition: background-color 0.3s ease;
      
      &:hover {
        background: #f8f9fa;
      }
      
      &.selected {
        background: #e3f2fd;
        border-left: 4rpx solid #007bff;
      }
      
      .option-text {
        font-size: 28rpx;
        color: #333;
      }
      
      .option-check {
        font-size: 32rpx;
        color: #007bff;
        font-weight: bold;
      }
    }
  }
  
  // 房间状态更新模态框的特殊样式
  .modal-body {
    padding: 30rpx;
    
    .current-status-info {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      padding: 20rpx;
      background: #f8f9fa;
      border-radius: 12rpx;
      
      .info-label {
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
        margin-right: 15rpx;
      }
      
      .info-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
      }
      
      .status-badge {
        padding: 8rpx 20rpx;
        border-radius: 20rpx;
        font-size: 24rpx;
        font-weight: bold;
        
        &.status-wait { background: #fff3cd; color: #856404; }
        &.status-prepare { background: #d1ecf1; color: #0c5460; }
        &.status-countdown { background: #d4edda; color: #155724; }
        &.status-start { background: #cce5ff; color: #004085; }
        &.status-stop { background: #f8d7da; color: #721c24; }
        &.status-pause { background: #fff3cd; color: #856404; }
        &.status-cancel { background: #f8d7da; color: #721c24; }
        &.status-error { background: #f8d7da; color: #721c24; }
        
        // 席位状态样式
        &.status-idle { background: #d4edda; color: #155724; }
        &.status-occupy { background: #cce5ff; color: #004085; }
        &.status-ready { background: #fff3cd; color: #856404; }
        &.status-prepare { background: #d1ecf1; color: #0c5460; }
        &.status-plan { background: #e2e3e5; color: #383d41; }
        &.status-matching { background: #d4edda; color: #155724; }
        &.status-end { background: #f8d7da; color: #721c24; }
      }
    }
    
    .next-status-section {
      .section-title {
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
        margin-bottom: 20rpx;
        display: block;
      }
      
      .status-options {
        .status-option {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 25rpx;
          border: 2rpx solid #eee;
          border-radius: 12rpx;
          margin-bottom: 15rpx;
          transition: all 0.3s ease;
          cursor: pointer;
          
          &:hover {
            border-color: #667eea;
            background: #f8f9fa;
          }
          
          &.selected {
            border-color: #667eea;
            background: #e3f2fd;
            border-left: 4rpx solid #667eea;
          }
          
          .option-text {
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
          }
          
          .option-check {
            font-size: 32rpx;
            color: #667eea;
            font-weight: bold;
          }
        }
      }
    }
  }
  
  .modal-footer {
    display: flex;
    gap: 20rpx;
    padding: 30rpx;
    border-top: 2rpx solid #eee;
    
    .cancel-btn, .submit-btn {
      flex: 1;
      height: 80rpx;
      border: none;
      border-radius: 12rpx;
      font-size: 28rpx;
      font-weight: bold;
      
      &.cancel-btn {
        background: #f8f9fa;
        color: #666;
        border: 2rpx solid #eee;
      }
      
      &.submit-btn {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        color: #fff;
        
        &:disabled {
          opacity: 0.6;
        }
      }
    }
  }
}

// 降低模态框的z-index，避免遮挡picker
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .modal-content {
    width: 90%;
    max-height: 80%;
    background: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    position: relative;
    z-index: 10000;
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 2rpx solid #eee;
      
      .modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close-btn {
        width: 60rpx;
        height: 60rpx;
        border: none;
        background: none;
        font-size: 40rpx;
        color: #999;
      }
    }
    
    .modal-body {
      padding: 30rpx;
      max-height: 60vh;
      overflow-y: auto;
      
      .form-section {
        .form-item {
          margin-bottom: 25rpx;
          position: relative;
          z-index: 1;
          
          .form-label {
            display: block;
            font-size: 26rpx;
            color: #333;
            font-weight: bold;
            margin-bottom: 10rpx;
          }
          
          .form-input {
            width: 100%;
            height: 70rpx;
            padding: 0 15rpx;
            border: 2rpx solid #ddd;
            border-radius: 8rpx;
            font-size: 26rpx;
            background: #fff;
            box-sizing: border-box;
            
            &:focus {
              border-color: #667eea;
            }
          }
          
          .form-picker {
            width: 100%;
            height: 70rpx;
            border: 2rpx solid #ddd;
            border-radius: 8rpx;
            background: #fff;
            position: relative;
            z-index: 2;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 15rpx;
            cursor: pointer;
            box-sizing: border-box;
            
            .picker-text {
              font-size: 26rpx;
              color: #333;
            }
            
            .picker-arrow {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
      }
    }
    
    .modal-footer {
      display: flex;
      gap: 20rpx;
      padding: 30rpx;
      border-top: 2rpx solid #eee;
      
      .cancel-btn, .submit-btn {
        flex: 1;
        height: 80rpx;
        border: none;
        border-radius: 12rpx;
        font-size: 28rpx;
        font-weight: bold;
        
        &.cancel-btn {
          background: #f8f9fa;
          color: #666;
          border: 2rpx solid #eee;
        }
        
        &.submit-btn {
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
          color: #fff;
          
          &:disabled {
            opacity: 0.6;
          }
        }
      }
    }
  }
}

// WebSocket连接控制样式
.ws-connection-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
  margin-top: 20rpx;
  margin-bottom: 10rpx;
  .ws-status-label {
    font-size: 26rpx;
    color: #fff;
    margin-right: 10rpx;
  }
  .ws-status-indicator {
    padding: 6rpx 18rpx;
    border-radius: 16rpx;
    font-size: 22rpx;
    font-weight: bold;
    margin-right: 10rpx;
    &.connected { background: #d4edda; color: #155724; }
    &.disconnected { background: #f8d7da; color: #721c24; }
  }
  .ws-connect-btn, .ws-disconnect-btn {
    padding: 6rpx 20rpx;
    border: none;
    border-radius: 10rpx;
    font-size: 22rpx;
    font-weight: bold;
    color: #fff;
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    &:disabled { opacity: 0.6; }
  }
  .ws-disconnect-btn {
    background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
  }
}

</style> 